/**
 *@author lxc
 *@description://防抖处理，并发处理,主要@click 替换成v-btnAntiShake
 *@param:
 *@date: 2022-07-19 14:07:25
 **/
import { App, DirectiveBinding } from 'vue'
export default (app: App<Element>) => {
  app.directive('btnAntiShake', {
    mounted(el: HTMLElement, binding: DirectiveBinding) {
      let timer: NodeJS.Timeout | null = null
      let timer2: NodeJS.Timeout | null = null
      // 秒数，通过改变该值直接改变整个函数的时间,不用逐个改
      const second = 3
      // 储存按钮名称
      const originalText = el.childNodes.item(1).textContent

      el.addEventListener('click', () => {
        let duration = second

        const firstClick: Boolean = !timer
        if (firstClick) {
          binding.value()
        }
        if (timer) {
          clearTimeout(timer)
        }
        if (timer2) {
          // 还原秒数清理间隔触发器.
          duration = second
          clearInterval(timer2)
        }
        timer = setTimeout(() => {
          timer = null
          if (!firstClick) {
            // binding.value()
          }
        }, second * 1000)
        // 每隔一秒减少1秒,3秒后变回原来的按钮文本
        timer2 = setInterval(() => {
          // 改变el对象里的span标签文本
          el.childNodes.item(1).textContent = (--duration).toString()
          if (duration <= 0) {
            el.childNodes.item(1).textContent = originalText
            clearInterval(timer2!)
          }
        }, 1000)
      })
    }
  })
}
